package tool;

import entity.*;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

public class CardUtil {
    public Map<String, MobileCard> mobileCardMap = new HashMap<>();
    public Map<String, List<ConsumInfo>> consumInfoMap = new HashMap<>();
    public Scene initScene(int id){//根据传来的ID号产生模拟的消费场景并返回
        Scene scene = null;
        switch (id){
            case 0:
                scene = new Scene("通话",90,"问候客户，谁知如此难缠，通话90分钟");
                break;
            case 1:
                scene = new Scene("通话",30,"问候妈妈身体，通话30分钟");
                break;
            case 2:
                scene = new Scene("短信",5,"参与学校的论文答辩与老师发短信5");
                break;
            case 3:
                scene = new Scene("短信",50,"通知朋友换手机号，发送短信50条");
                break;
            case 4:
                scene = new Scene("上网",1024,"和女友微信视频聊天，使用流量1GB");
                break;
            case 5:
                scene = new Scene("上网",2048,"晚上手机看电影，不留神睡着了，使用流量2GB");
                break;
        }
        return scene;
    }
    public void addCard(MobileCard card){//将这个手机卡添加到集合中
        mobileCardMap.put(card.getCardNumber(),card);
    }
    public MobileCard find(String number){//查询方法，若在集合中查找到指定的手机卡则返回这个卡对象，否则返回null
        MobileCard temp = null,search = null;
        for (Map.Entry<String,MobileCard> mobCard: mobileCardMap.entrySet()) {
            temp = mobCard.getValue();
            if (temp != null && number.equals(temp.getCardNumber())) {
                search = temp;
                break;
            }
        }

        return search;
    }
    public boolean find(String number,String password){//和上面的方法构成重载，参数多一个密码，功能类似
        boolean isexist = false;
        MobileCard temp = null;
        for (Map.Entry<String,MobileCard> mobileCard: mobileCardMap.entrySet()) {
            temp = mobileCard.getValue();
            if (temp != null && number.equals(temp.getCardNumber()) && password.equals(temp.getPassword())) {
                isexist = true;
                break;
            }
        }
        return isexist;
    }
    public void chargeMoney(String number,double money){//充值方法
        MobileCard temp = null;
        temp = find(number);
        if (null != temp) {
            temp.setMoney(temp.getMoney() + money);
            System.out.println("充值成功！");
        }else{
            System.out.println("充值失败！,不存在此卡");
        }
    }
    public void showBillDetail(String number){//查看账单
        MobileCard temp = null;
        temp = find(number);
        if (temp != null) {
            System.out.println("当月账单：");
            BigDecimal bigDecimal = new BigDecimal(temp.getSerPackage().getPrice()).setScale(1, RoundingMode.DOWN);
            System.out.println("套餐资费：" + bigDecimal.doubleValue() + "元");
            bigDecimal = new BigDecimal(temp.getConsume()).setScale(1, RoundingMode.DOWN);//控制double类型数据的小数位数
            System.out.println("合计：" + bigDecimal.doubleValue() + "元");
            bigDecimal = new BigDecimal(temp.getMoney()).setScale(1, RoundingMode.DOWN);
            System.out.println("账单余额：" + bigDecimal.doubleValue() + "元");
        }else {
            System.out.println("你输入的号码有误！");
        }
    }
    public void showRemaingDetail(String number){//显示套餐余量信息
        MobileCard temp = null;
        int talkTime = 0,massageCount = 0,flow = 0;
        temp = find(number);
        if (temp != null) {
            System.out.println("套餐余量：");
            if (temp.getSerPackage() instanceof TalkPackage) {
                //要判断传来的手机号对象的卡办理的是否是话痨套餐，因为想要调用当中的子类独有方法
                talkTime = ((TalkPackage) temp.getSerPackage()).getTalkTime() - temp.getRealTalkTime();
                massageCount = ((TalkPackage) temp.getSerPackage()).getMessageCount() - temp.getRealMassageNumbers();
                if (talkTime > 0) {
                    System.out.println("通话时长：" + talkTime + "分钟");
                }else{
                    System.out.println("通话时长：0分钟");
                }
                if (massageCount > 0) {
                    System.out.println("短信条数：" + massageCount + "条");
                }else{
                    System.out.println("短信条数：0条");
                }
                System.out.println("上网流量：0MB");
            }else if (temp.getSerPackage() instanceof NetPackage){//和上面类似，只不过换成网虫套餐
                flow = ((NetPackage)temp.getSerPackage()).getFlow() - temp.getRealFlow();
                System.out.println("通话时长：0分钟");
                System.out.println("短信条数：0条");
                if (flow > 0) {
                    System.out.println("上网流量：" + flow + "MB");
                }else{
                    System.out.println("上网流量：0MB");
                }
            }else{//和上面类似
                talkTime =((SuperPackage)temp.getSerPackage()).getTalkTime() - temp.getRealTalkTime();
                massageCount = ((SuperPackage)temp.getSerPackage()).getMessageCount() - temp.getRealMassageNumbers();
                flow = ((SuperPackage)temp.getSerPackage()).getFlow() - temp.getRealFlow();
                if (talkTime > 0) {
                    System.out.println("通话时长：" + talkTime + "分钟");
                }else{
                    System.out.println("通话时长：0分钟");
                }
                if (massageCount > 0) {
                    System.out.println("短信条数：" + massageCount + "条");
                }else{
                    System.out.println("短信条数：0条");
                }
                if (flow > 0) {
                    System.out.println("上网流量：" + flow + "MB");
                }else{
                    System.out.println("上网流量：0MB");
                }
            }

        }
    }
    public BrandPackage choosePack(int packId){//根据编号选择套餐
        BrandPackage brandPackage = null;
            switch (packId){
                case 1:
                    brandPackage = new TalkPackage();
                    break;
                case 2:
                    brandPackage = new NetPackage();
                    break;
                case 3:
                    brandPackage = new SuperPackage();
                    break;
                default:
                    System.out.println("输入的选项错误");
                    break;
            }
        return brandPackage;
    }
    public void changePack(String number,int packId){//套餐的变更
        MobileCard temp = null;
        BrandPackage bp = null;
        int choose = -1,myPack = -1;
        bp = choosePack(packId);
        if (bp instanceof TalkPackage) {
            choose = 1;
            bp.setPrice(58);
        }else if(bp instanceof NetPackage){
            choose = 2;
            bp.setPrice(68);
        }else {
            choose = 3;
            bp.setPrice(78);
        }
        temp = find(number);
        if (temp == null) {
            System.out.println("你输入的号码有误");
            return;
        }else {
            if (temp.getSerPackage() instanceof TalkPackage) {
                myPack = 1;
            }else if(temp.getSerPackage() instanceof NetPackage){
                myPack = 2;
            }else {
                myPack = 3;
            }
        }
        if (choose == myPack) {//通过对卡的套餐的判定而相应的转化为整数，从而判断是否是同一种套餐
            System.out.println("对不起，你已是该套餐用户，无需更改");
        }else if (temp.getMoney() < bp.getPrice()) {//如果余额不足则不予办理，并提醒
            System.out.println("对不起，你的余额已不足支付新的套餐资费，请先充值，再更换套餐");
        }else{//办理成功时，进行相应的数据重置
            temp.setRealFlow(0);
            temp.setRealMassageNumbers(0);
            temp.setRealTalkTime(0);
            temp.setSerPackage(bp);
            temp.setMoney(temp.getMoney() - bp.getPrice());
            temp.setConsume(bp.getPrice());
            System.out.print("更换套餐成功!");
            bp.show();
        }
    }
    public void deleteCard(String number){//退网，退掉此卡，即从集合中删除它
        MobileCard temp = null;
        temp = find(number);
        if (temp != null) {
            mobileCardMap.remove(number);
            System.out.println("卡号" + number + "办理退网成功！");
            System.out.println("谢谢使用");
            System.exit(0);
        }
    }
    public String createNumber(){//随机创造一个手机号
        StringBuffer target = new StringBuffer();
        target.append("139");
        int numberLen = 8,choose = -1;
        for (int i = 0; i < numberLen; i++) {
            choose = (int)(Math.random() * (9 - 1 + 1) + 1);
            switch (choose){
                case 0:target.append("0");
                    break;
                case 1:target.append("1");
                    break;
                case 2:target.append("2");
                    break;
                case 3:target.append("3");
                    break;
                case 4:target.append("4");
                    break;
                case 5:target.append("5");
                    break;
                case 6:target.append("6");
                    break;
                case 7:target.append("7");
                    break;
                case 8:target.append("8");
                    break;
                default:target.append("9");
                    break;
            }
        }
        return target.toString();
    }
    public String[] getNewNumber(int count){//产生可供用户选择的手机号的具体方法
        String[] list = new String[count];
        MobileCard temp = null;
        String tempStr = null;
        boolean isExist = false;
        for (int i = 0; i < list.length; i++) {
            tempStr = createNumber();
            for (Map.Entry<String,MobileCard> mobCard: mobileCardMap.entrySet()) {
                temp = mobCard.getValue();
                if (temp.getCardNumber().equals(tempStr)) {
                    isExist = true;
                    break;
                }
            }

            if (!isExist) {
                list[i] = tempStr;
            }else{
                i--;
                isExist = false;
            }
        }
        return list;
    }
    public void showPriceDescription(){//显示资费信息
        BufferedReader br = null;
        String content = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\项目\\搜搜移动业务大厅\\SosoMgr\\套餐资费说明.txt"),"UTF-8"));
            while ((content = br.readLine()) != null){
                System.out.println(content);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public List findConsumInfo(String number){//根据手机号，查找相应的手机卡的消费记录集合并返回
        List<ConsumInfo> list = null;
        for (Map.Entry<String,List<ConsumInfo>> cardNum:consumInfoMap.entrySet()) {
            if (cardNum.getKey().equals(number)) {
                list = cardNum.getValue();
                break;
            }
        }
        return list;
    }
    public void addConsumInfo(String number,ConsumInfo info){//当产生消费时，要将消费记录添加到指定集合中
        List<ConsumInfo> list = null;
        list = findConsumInfo(number);
        if (list == null) {//如果是null就是第一次消费，则创建一个列表，并把它加进去
            list = new ArrayList<ConsumInfo>();
            list.add(info);
            consumInfoMap.put(number,list);
        }else {
            list.add(info);
        }
        System.out.println("添加成功!");
    }
    public void printConsumeDetail(String number){//打印该手机卡的消费记录到一个文本文件中
        List<ConsumInfo> list = null;
        list = findConsumInfo(number);
        PrintWriter out = null;
        int i = 1;
        if (list == null) {
            System.out.println("对不起，不存在此卡的消费记录！");
        }else{
            try {
                out = new PrintWriter(new FileOutputStream("D:\\JAVAIDEA\\test.txt"),true);
                out.println("******" + number + "消费记录******");
                out.flush();
                out.println("序号     类型      数据（通话（条）/上网（MB）/短信（条））");
                out.flush();
                for (ConsumInfo consumInfo:list) {
                    out.println(i + "\t" + consumInfo.getType() + "\t\t" + consumInfo.getConsumData());
                    out.flush();
                    i++;
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }finally {
                out.close();
            }
        }
    }
    public void userSoso(String number) {
        MobileCard temp = null;
        boolean isError = false;
        int myPack = -1,choose = -1;
        Scene scene = null;
        temp = find(number);
        TalkPackage talkPackage = null;
        NetPackage netPackage = null;
        SuperPackage superPackage = null;
        ConsumInfo consumInfo = null;
        if (temp != null) {//为了与手机卡相对应，必须要判断此绑定的套餐是哪一种套餐，为了后面产生相应的消费场景
            if (temp.getSerPackage() instanceof TalkPackage) {//也可以判断此类是否是接口的实现类
                myPack = 1;
            }else if(temp.getSerPackage() instanceof NetPackage){
                myPack = 2;
            }else {
                myPack = 3;
            }
            do{
                choose = (int )(Math.random() * 6);
                try {
                    if (myPack == 1 && choose != 4 && choose != 5) {
                        scene = initScene(choose);
                        talkPackage = (TalkPackage)temp.getSerPackage();
                        if (scene.getType().equals("通话")) {
                            talkPackage.call(scene.getData(),temp);
                        }else {
                            talkPackage.send(scene.getData(),temp);
                        }
                        break;
                    }else if (myPack == 2 && (choose == 4 || choose == 5)) {
                        scene = initScene(choose);
                        netPackage = (NetPackage) temp.getSerPackage();
                        netPackage.netPlay(scene.getData(),temp);
                        break;
                    }else if (myPack == 3) {
                        scene = initScene(choose);
                        superPackage = (SuperPackage)temp.getSerPackage();
                        if (scene.getType().equals("通话")) {
                            superPackage.call(scene.getData(),temp);
                        }else if (scene.getType().equals("短信")) {
                            superPackage.send(scene.getData(),temp);
                        }else {
                            superPackage.netPlay(scene.getData(),temp);
                        }
                        break;
                    }
                }catch (Exception e){//费用透支时，产生异常信息
                    e.printStackTrace();
                    isError = true;
                    break;
                }
            }while(true);
            System.out.println(scene.getDescription());
            if (!isError) {
                consumInfo = new ConsumInfo(number,scene.getType(),String.valueOf(scene.getData()));
                addConsumInfo(number,consumInfo);
            }else {
                isError = false;
            }
        }else{
            System.out.println("输入错误！");
        }

    }
}
